package zheezes.util;

public class CRC16CCITT {
	private int crc = 0;
	private int poly = 0x8408;

	public int getValue() {
		return crc;
	}

	public void reset() {
		crc = 0;
	}

	public void update(byte[] buf) {
		update(buf, 0, buf.length);
	}

	public void update(byte[] buf, int offset, int len) {
		int max = offset + len;
		int carry;
		for (int i = offset; i < max; i++) {
			crc = crc ^ buf[i];
			for (int ibit = 0; ibit < 8; ibit++) {
				carry = crc & 1;
				crc = crc >> 1;
				if (carry != 0) {
					crc = crc ^ poly;
				}
			}
		}
	}

	public static void main(String[] args) {
		byte[] buf = new byte[] { 0x0B, 0x20, 0x43, 0x06, 0x01, 0x00, 0x00,
				0x02, 0x01 };
		CRC16CCITT cc = new CRC16CCITT();
		cc.update(buf, 0, 1);
		cc.update(buf, 1, buf.length - 1);
		System.out.printf("%X", cc.getValue());
	}
}
